package com.admin.system.auth.service;

import java.util.HashSet;
import java.util.Set;

import com.admin.system.entity.SystemUser;
import com.admin.system.service.SystemUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.admin.system.auth.entity.LoginToken;
import com.admin.system.auth.entity.Permission;
import com.admin.system.auth.entity.Role;
import com.admin.system.auth.entity.ShiroUser;

public class SystemShiroRealm extends AuthorizingRealm {

	// 用户查询
	@Autowired
    SystemUserService userService;
	@Autowired
	AccoutAuthService authService;

	// 角色权限和对应权限添加
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 获取登录名
		SystemUser user = (SystemUser) principals.getPrimaryPrincipal();
		// 查询用户
		ShiroUser shiroUser = userService.queryShiroUser(user.getId());
		// 添加角色和权限
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		Set<Role> roleSet = shiroUser.getRoleSet();

		// 角色名的集合
		Set<String> roles = new HashSet<String>();
		// 权限名的集合
		Set<String> permissions = new HashSet<String>();
		for (Role role : roleSet) {
			roles.add(role.getName());
			for (Permission per : role.getPermissionSet()) {
				permissions.add(per.getName());
			}
		}
		simpleAuthorizationInfo.addRoles(roles);
		simpleAuthorizationInfo.addStringPermissions(permissions);
		return simpleAuthorizationInfo;
	}

	// 用户认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 加这一步的目的是在Post请求的时候会先进认证，然后在到请求
		LoginToken loginToken = (LoginToken) token;
		if (loginToken.getPrincipal() == null) {
			return null;
		}
		// 认证用户登录信息
		SystemUser user = authService.checkLoginToken(loginToken);
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, token.getCredentials(),
				getName());
		return simpleAuthenticationInfo;
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		if (token instanceof LoginToken) {
			return true;
		}
		return false;
	}

}
